package com.xiaochong.bitong.job.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Project : XiaoChongService
 * @Package Name : com.xiaochong.service.user.asyn
 * @Description : TODO
 * @Author : daizhiqing@xiaochong.com
 * @Creation Date : 2018年05月11日下午1:40
 * @ModificationHistory Who When What
 */

@Configuration
@EnableAsync
public class ExecutorConfig {
    private int corePoolSize = 10;
    private int maxPoolSize = 100;
    private int queueCapacity = 10;

    /**
     * 邀请异步通知的执行线程池
     */
    public static final String SCHEDULER_EXECUTOR_POOL = "bitongAppJobExecutorPool";
    /**
     * 邀请异步通知的执行线程池
     * @return
     */
    @Bean
    public Executor bitongAppJobExecutorPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(SCHEDULER_EXECUTOR_POOL);

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
